# -*- coding: utf-8 -*-

import sys, os
try:
        import pygtk
        pygtk.require("2.0")
except:
        pass
try:
        import gtk
        import gtk.glade
except:
        sys.exit(1)
from simpledcpp.core.base import DCPPPart, DCPPEvent
from simpledcpp.gui.widgets.list import QueueTree
from simpledcpp.gui.HumanReadableSize import HRS
from simpledcpp.gui.base import gtk_lock_required
class QueuePage(DCPPPart):
	def activate(self, *args, **kwargs):
		size = 0
		for i in self.tasks:
			size = i.filesize + size
		self.Event(DCPPEvent("LSB",(_("Must downloaded") + " %s"%self.HRS.byteToHuman(size),)))

	def __init__(self, parent):
		DCPPPart.__init__(self, parent)
		sw = gtk.ScrolledWindow()
		sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
		self.name = _('Queue')
		self.type = 'queue'
		menu_items = (
		( "/_" + _("Search for alternates"), 'Search', self._alternates, 0, None),
		( "/_" + _("Remove") , 'Remove', self._needremove, 0, None),
#                ( "/_Очень низкий приоритет" , 'PR', self._priority, 0, None),
 #               ( "/_Низкий приоритет" , 'PRi1', self._priority, 0, None),
  #              ( "/_Средний приоритет" , 'PR', self._priority, 0, None),
   #             ( "/_Высокий приоритет" , 'PR', self._priority, 0, None),
    #            ( "/_Очень высокий приоритет" , 'PR', self._priority, 0, None),
		)
		self._tree = QueueTree(menu_items)
		self.HRS = HRS()
		self._load()
		self.Events.Subscribe("QUEUE_UPDATED", self._update)
		self.Events.Subscribe("ON_NEW_TASK", self._new)
		self.Events.Subscribe("ON_REMOVE_TASK", self._remove)
		sw.add(self._tree.widget)
		sw.show()
		self._widget = sw

	def _priority(self, *args, **kwargs):
		print args

	def _alternates(self, *args, **kwargs):
		tth = self._tree.selected_rows[5]
		self.Event(DCPPEvent("SEARCH_TTH",(tth,)))


	def _load(self, *args, **kwargs):
		self.tasks = {}
		self._tree.clear()
		for task in self.queue:
			filename = task.localfilename
			filesize = self.HRS.byteToHuman(int(task.filesize))
			status = int(task.segment.percent())
			if int(status) < 0:
				status = 0
			priority = int(task.priority)
			sources = ""
			for i in task.sources.generator():
				sources = sources +  "[%s:%s],"%(i.nickname, i.hubname)
			tth = task.TTH
			self.tasks[task] = self._tree.append((filename, status, filesize,priority, sources, tth, task.filesize))

	@gtk_lock_required
	def _new(self, Event):
		task = Event.userdata[0]
		filename = task.localfilename
                filesize = self.HRS.byteToHuman(int(task.filesize))
                status = task.segment.percent()
		if int(status) < 0:
			status = 0
                priority = task.priority
                sources = ""
                for i in task.sources.generator():
                	sources = sources +  "[%s:%s],"%(i.nickname, i.hubname)
                tth = task.TTH
                self.tasks[task] = self._tree.append((filename, status,filesize, priority, sources, tth, task.filesize))

	@gtk_lock_required
	def _update(self, Event):
		task = Event.userdata[0]
		try:
			iter = self.tasks[task]
		except:
			return
		status = task.segment.percent()
		if int(status)<0:
			status = 0
		self._tree.update(iter, 1, status)
		sources = ""
		for i in task.sources.generator():
			sources = sources + "[%s:%s],"%(i.nickname, i.hubname)
		self._tree.update(iter, 4, sources)
	
	@gtk_lock_required
	def _remove(self, Event):
		task = Event.userdata[0]
		iter = self.tasks.pop(task)
		self._tree.remove(iter)

	@gtk_lock_required
	def _needremove(self, *args, **kwargs):
		filename = self._tree.selected_rows[0]
		removed = None
		for i in self.tasks:
			if i.localfilename == filename:
				self.Event(DCPPEvent("REMOVE_TASK", (i,)))
				removed = i
		if removed != None:
			iter = self.tasks.pop(removed)
			self._tree.remove(iter)

	def Close(self, *args, **kwargs):
                self.Events.Unsubscribe("QUEUE_UPDATED", self._update)
                self.Events.Unsubscribe("ON_NEW_TASK", self._new)
                self.Events.Unsubscribe("ON_REMOVE_TASK", self._remove)
